﻿using System;
using System.Web.Mvc;
using cludg.Web.Core.Utils;
using Recaptcha;

namespace cludg.Web.Core.Captcha
{
	using Controllers;

	public delegate bool NeedChaptchaDelegate();

	public class CaptchaValidator : ActionFilterAttribute
	{
		private const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";
		private const string RESPONSE_FIELD_KEY = "recaptcha_response_field";
		private const string CAPTCHA_MODEL_KEY = "Captcha";

		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			var controller = filterContext.Controller as BaseController;
			if (controller == null)
			{
				throw new ApplicationException("CaptchaValidator filter can be user only with BaseController objects.");
			}
			
			if (CaptchaUtil.NeedUseCaptcha(controller))
			{
				var captchaChallengeValue = filterContext.HttpContext.Request.Form[CHALLENGE_FIELD_KEY];
				var captchaResponseValue = filterContext.HttpContext.Request.Form[RESPONSE_FIELD_KEY];
				var captchaValidtor = new RecaptchaValidator
				                      	{
				                      		PrivateKey = controller.Settings["ReCAPTHA_PrivateKey"].ToString(),
				                      		RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
				                      		Challenge = captchaChallengeValue,
				                      		Response = captchaResponseValue
				                      	};

				var recaptchaResponse = captchaValidtor.Validate();
				
				if (!recaptchaResponse.IsValid)
				{
					filterContext.Controller
						.ViewData.ModelState
						.AddModelError(
							CAPTCHA_MODEL_KEY,
							"Совсем не тот текст");
				}
			}

			base.OnActionExecuting(filterContext);
		}
	}
}
